package kite.sso.aspect;

import kite.sso.config.KiteSsoConfig;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 功能描述: <br>
 * 所属包名: kite.sso.aspect<br>
 * 创建人　: 白剑<br>
 * 创建时间: 06/07/2018 10:53 Thursday<br>
 * 当前版本: 1.0<br>
 * 修改历史: <br>
 * 修改时间　　　　　修改人　　　　　版本变更　　　　　修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@Aspect
@Component
public class LoggingAspect {

    private static Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

    @Pointcut("execution(public * kite.sso.controller..*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void before(JoinPoint joinPoint) {
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == attributes) {
            return;
        }

        HttpServletRequest request = attributes.getRequest();

        System.out.println();
        logger.info("请求开始：{}", joinPoint.getTarget().getClass().getName());
        logger.info("URL: {}", request.getRequestURL().toString());
        logger.info("HTTP_METHOD: {}", request.getMethod());
        logger.info("CLASS: {}, METHOD: {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName());
        logger.info("ARGS: {}", Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void afterReturning(Object ret) {
        if (ret != null && ret.equals(KiteSsoConfig.ERROR_PATH)) {
            return;
        }
        logger.info("请求处理完成，返回内容：{}", ret);
        System.out.println();
    }

    @Around("webLog()")
    public Object arround(ProceedingJoinPoint pjp) {
        try {
            return pjp.proceed();
        } catch (Throwable e) {
            logger.error("AOP日志处理异常，", e);
            return null;
        }
    }
}
